import { BusinessType } from '../constants/BusinessType';
import { Business } from '../modal/Business';

/**
 * @author 田尘殇Sean(sean.snow@live.com) createAt 2017/12/21
 */
export function isQuickPay(businessType) {
  return businessType.startsWith('QUICK');
}

export function isQuickPaySn(businessType) {
  return isQuickPay(businessType) && businessType.endsWith('_SN');
}

export function isQuickGatePay(businessType: string) {
  return isQuickPay(businessType) && businessType.includes("GATE");
}

export function isAliPay(businessType) {
  return businessType.startsWith('AliPay');
}

export function isWeChatPay(businessType) {
  return businessType.startsWith('WeChat');
}

export function isUnionPay(businessType) {
  return businessType.startsWith('UNION_PAY');
}

export function isUnionScanPay(businessType) {
  return businessType.startsWith('UNION_SCAN_QRCODE_PAY');
}

export function getAdvBusinessType(businessType) {
  if (isQuickPaySn(businessType)) {
    return BusinessType.quickPaySn;
  }
  if (isQuickPay(businessType)) {
    return BusinessType.quickPay;
  }
  if (isAliPay(businessType)) {
    return BusinessType.aliPay;
  }
  if (isWeChatPay(businessType)) {
    return BusinessType.weChatPay;
  }

  return businessType;
}

export function getFeeRateTypeText(feeRateType) {
  if (feeRateType === 'CAP') {
    return '元';
  }
  return '%';
}

function calculate(feeRateType, feeRate, minFee, amount) {
  let value = 0;
  if (feeRateType === 'CAP') {
    value = feeRate * 1;
  } else {
    value = amount * (feeRate / 100);
  }
  if (value < minFee * 1) {
    return minFee * 1;
  }
  let valueStr = value.toString();
  if (valueStr.substr(valueStr.indexOf('.')).length > 3) {
    value = +value.toFixed(2) + 0.01;
  }
  return value;
}

export function calculateFeeRate({
                                   feeRateType,
                                   feeRate,
                                   minFee,
                                   serviceFeeRateType,
                                   serviceFeeRate,
                                   minServiceFee
                                 }, amount) {
  return calculate(feeRateType, feeRate, minFee, amount) + calculate(serviceFeeRateType, serviceFeeRate, minServiceFee, amount);
}


export function findBusiness(businessType, businesses: Array<Business>) {
  let business = businesses.find(item => item.businessType === businessType);
  if (!business) {
    business = businesses.find(item => item.businessType === getAdvBusinessType(businessType));
  }
  return business;
}

